<script setup>
import { ref, reactive } from 'vue'
//图片地址数组
const imgs = [
  "src/assets/imgs/1.jpeg",
  "src/assets/imgs/2.jpeg",
  "src/assets/imgs/3.jpeg",
]
//用于绑定的当前图片地址
const imgurl = ref(imgs[0])
//当前显示的图片索引
const index = ref(0)

//上一张
const prevclick = () => {
  index.value = index.value === 0 ? imgs.length - 1 : index.value - 1
  imgurl.value = imgs[index.value]
  updateDotActiveClass()
}
//下一张
const nextclick = () => {
  index.value = index.value === imgs.length - 1 ? 0 : index.value + 1
  imgurl.value = imgs[index.value]
  updateDotActiveClass()
}

//每隔3秒切换下一张
const intervalId = setInterval(() => {
  nextclick()
}, 3000)

//点击小圆点
const dotclick = (i) => {
  index.value = i
  imgurl.value = imgs[index.value]
  updateDotActiveClass()
}

const updateDotActiveClass = () => {
  const dots = document.querySelectorAll('.dot')
  dots.forEach((dot, i) => {
    if (i === index.value) {
      dot.classList.add('active')
    } else {
      dot.classList.remove('active')
    }
  })
}

</script>

<template>
  <div class="carousel">
    <img :src="imgurl" alt="">
    <span class="prev" @click="prevclick">&lt;</span>
    <span class="next" @click="nextclick">&gt;</span>

    <div class="dots">
      <!-- 使用v-for 修改下面的代码 , 点击小圆点时，相应的图显示 -->
      <span v-for="(img, i) in imgs" :key="i" :class="{ 'dot': true, 'active': i === index.value }" @click="dotclick(i)"></span>
    </div>

  </div>
</template>

<style>
.carousel {
  width: 1000px;
  height: 240px;
  overflow: hidden;
  position: relative;
  margin: 0 auto;
}
.carousel img {
  width: 1000px;
  height: 240px;
}
.carousel .prev,
.carousel .next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 10px;
  cursor: pointer;
}
.carousel .prev {
  left: 0;
}
.carousel .next {
  right: 0;
}
.dots {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
}
.dot {
  width: 10px;
  height: 10px;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 50%;
  margin: 0 5px;
  cursor: pointer;
}
/* 当前小圆点的样式 */
.dot.active {
  background-color: #fff;
}
</style>